'use strict'

const {Blog,Op} = require('../model')

let fn_index = async (ctx,next)=>{
    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

let fn_data = async (ctx,next)=>{
    let keyword = ctx.request.query.keyword

    if (keyword !== '') {
        if (isNaN(keyword)==false) {
            let data = await Blog.findAll({
                where:{
                    [Op.or]:[
                        {id:keyword}
                    ]
                }
            })
            ctx.body = data
        } else {
            let data = await Blog.findAll({
                where:{
                    [Op.or]:[
                        {title:keyword},
                        {digest:keyword},
                        {content:keyword},
                        {type:keyword},
                        {author:keyword},
                    ]
                }
            })
            ctx.body = data
        }
    } else {
        await Blog.findAll().then(res=>{
            ctx.body=res
        })
    }
}

let fn_add = async (ctx,next)=>{
    let data = await Blog.findAll().then(res=>{
        let max = 0
        for(let i in res){
            if (max<res[i].id) {
                max = res[i].id
            }
        }
        let id = max +1
        let data = ctx.request.body
        data.id = id
        return data
    })

    await Blog.create(data)
    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

let fn_edit =async (ctx,next)=>{
    let data = ctx.request.body
    await Blog.findByPk(data.id).then(async post=>{
        await post.update({
            id:data.id,
            title:data.title,
            digest:data.digest,
            content:data.content,
            type:data.type,
            author:data.author,
        })
    })
    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

let fn_del = async (ctx,next)=>{
    let id = ctx.request.query.id
    await Blog.destroy({
        where:{id:id}
    })
    await Blog.findAll().then(res=>{
        ctx.body=res
    })
}

let get=[['/index',fn_index],['/data',fn_data],['/delete',fn_del]]
let post = [['/indexAdd',fn_add],['/indexEdit',fn_edit]]

module.exports = {
    "get":get,
    "post":post
}